/**
 * @Author: YU
 * @Date: 2021-10-23 22:11:47
 * @LastEditTime: 2021-10-25 20:10:56
 * @LastEditors: YU
 * @Description: Vue router
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Home from '@/views/Home'
import Welcome from '@/views/Welcome'
import Users from '@/views/Users'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 获取token
  const token = store.state.token
  if (!token) return next('/login')
  next()
})

export default router
